package com.ldzg.blockwatcher.utils;

import java.util.Objects;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;

/**
 * @author 18310740596@163.com
 * @version V1.0.0
 * @since 2025-02-10 10:15:01
 */
public class ThreadPoolUtil {
    private ThreadPoolUtil() {
    }

    private static volatile ExecutorService executorService;

    private static final Lock LOCK = new ReentrantLock();

    public static ExecutorService getExecutorService() {
        if (Objects.isNull(executorService)) {
            try {
                LOCK.lock();
                if (Objects.isNull(executorService)) {
                    ThreadFactory factory = Thread.ofVirtual().name("block-virtual-thread-", 1).factory();
                    ThreadPoolUtil.executorService = Executors.newThreadPerTaskExecutor(factory);
                }
            } finally {
                LOCK.unlock();
            }
        }
        return ThreadPoolUtil.executorService;
    }

    /**
     * 执行任务 不带返回值
     *
     * @param runnable 执行对象
     * @return 执行结果
     */
    public static CompletableFuture<Void> execute(Runnable runnable, Executor executor) {
        return CompletableFuture.runAsync(runnable, executor);
    }


    /**
     * 执行任务 不带返回值
     *
     * @param runnable 执行对象
     * @return 执行结果
     */
    public static CompletableFuture<Void> execute(Runnable runnable) {
        // 捕获父线程的上下文信息
        return execute(runnable, getExecutorService());
    }

    /**
     * 线程池执行任务 带返回值
     *
     * @param supplier 执行对象
     * @param <T>      结果对象类型
     * @return CompletableFuture
     */
    public static <T> CompletableFuture<T> submit(Supplier<T> supplier) {
        return CompletableFuture.supplyAsync(supplier, getExecutorService());
    }
}
